const buildFn = () => {
  const path = require("path");
  const fs = require("fs");
  const webpack = require("./webpack.config"); // webpack 配置对象
  // 以上代码请勿修改
  // TODO：待补充代码，所有代码请写在 `buildFn` 函数内
  let res = fs.readFileSync(path.join(__dirname, webpack.entry), "utf-8");
  res = res.split("\n");
  res.forEach((item, index) => {
    const reg = /import { \w+ } from '(@\w+)'/;
    if (reg.test(item)) {
      const matchs = reg.exec(item);
      res[index] = res[index].replace(
        matchs[1],
        webpack.output.resolve.alias[matchs[1]]
      );
    }
  });
  let list = "";
  res.forEach((item) => {
    list = list + item + "\n";
  });
  const rPath = webpack.output.path;
  fs.writeFileSync(`${rPath}/${webpack.output.filename}`, list);
  // 2.
  let htmlText = fs.readFileSync(path.join(__dirname, "index.html"), "utf-8");
  htmlText = htmlText
    .replace(/src="/g, `src="${webpack.output.publicPath}`)
    .replace(/href="/g, `href="${webpack.output.publicPath}`);
  fs.writeFileSync(`${rPath}/index.html`, htmlText);
  // 3.
  const folderPath = path.resolve(__dirname, "static");
  let distFilePath = path.resolve(webpack.output.path, "static");
  fs.mkdirSync(distFilePath);
  function copy(targetPath, distFilePath) {
    const files = fs.readdirSync(targetPath, "utf-8");
    for (const item of files) {
      let lastPath = path.resolve(targetPath, item);
      let lastdistFilePath = path.resolve(distFilePath, item);
      const fileStats = fs.statSync(lastPath);
      if (fileStats.isDirectory()) {
        fs.mkdirSync(lastdistFilePath);
        copy(lastPath, lastdistFilePath);
      } else {
        fs.copyFileSync(lastPath, lastdistFilePath);
      }
    }
  }
  copy(folderPath, distFilePath);
};

module.exports = buildFn;
